'''
Author: SlytherinGe
LastEditTime: 2021-03-07 18:59:33
'''
import cv2
import numpy as np
import xml.etree.ElementTree as ET
import os.path as osp
import os

def intersection_over_origin(target, origin):
    """calculate intersection of two boundboxes over the origin one.

    Args:
        target: list of xmin, ymin, xmax, ymax;
        origin: list of xmin, ymin, xmax, ymax;
    Returns:
        a float number of ioo between two inputs.
    """
    # determine the (x, y)-coordinates of the intersection rectangle
    xA = max(target[0], origin[0])
    yA = max(target[1], origin[1])
    xB = min(target[2], origin[2])
    yB = min(target[3], origin[3])

    # compute the area of intersection rectangle
    interArea = max(0, xB - xA + 1) * max(0, yB - yA + 1)

    OriginBoxArea = (origin[2] - origin[0] + 1) * (origin[3] - origin[1] + 1)

    ioo = interArea / float(OriginBoxArea)

    return ioo

def voc_basic_xml_element_generator(filename, folder, size_w, size_h, size_c):
    '''
    description: generat some common configs of a VOC label
    param {*}
    return {*}
    '''
    fd = ET.Element('folder')
    fd.text = folder
    sz = ET.Element('size')

    width = ET.Element('width')
    width.text = str(size_w)
    height = ET.Element('height')
    height.text = str(size_h)
    depth = ET.Element('depth')
    depth.text = str(size_c)
    for ele in (width, height, depth):
        sz.append(ele)

    return (fd, sz)

def voc_object_xml_element_resolver(object_element):
    '''
    description: convert the object element of a VOC xml into a dict
    param:
        object_element: the object to convert
    return:
        dict_obj: converted dict
    '''
    box = object_element.find('bndbox')
    dict_obj = {
        'name' : object_element.findtext('name'),
        'pose' : object_element.findtext('pose'),
        'truncated' : object_element.findtext('truncated'),
        'difficult' : object_element.findtext('difficult'),
        'bndbox' : {
            'xmin' : box.findtext('xmin'),
            'ymin' : box.findtext('ymin'),
            'xmax' : box.findtext('xmax'),
            'ymax' : box.findtext('ymax'),
        }
    }
    return dict_obj


def voc_object_xml_element_generator(object_dict):
    '''
    description: convert the dict of a VOC object into a XML element
    param:
        object_dict: the dict to convert
    return:
        obj: converted element
    '''
    obj = ET.Element('object')
    for k, v in object_dict.items():
        obj_ele = ET.Element(k)
        if k != 'bndbox':
            obj_ele.text = v
        else:
            for k1, v1 in v.items():
                obj_cord = ET.Element(k1)
                obj_cord.text = str(v1)
                obj_ele.append(obj_cord)
        obj.append(obj_ele)
    return obj
        
    